package com.weblog.serviceimp;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weblog.common.CommonInfo;
import com.weblog.mapper.user.BaseUserMapper;
import com.weblog.model.user.User;
import com.weblog.pojo.user.UserLogin;
import com.weblog.service.UserService;
import com.weblog.utils.ObjectUtils;
import com.weblog.utils.StringUtils;

@Service(value="userService")
public class UserServiceImp implements UserService {

	@Autowired
	private BaseUserMapper baseUserMapper;

	@Override
	public User getUserById(Integer userId) {
		User user = baseUserMapper.getUserById(userId);
		return user;
	}
	//用户注册
	@Override
	public int doRegiest(User user, String userPwdConfirm) {
		// 生成4位的随机字符串
		int result = 0;
		if (ObjectUtils.ObjectIsNotNull(user) && StringUtils.isNotNULL(user.getUserPwd()) && StringUtils.isNotNULL(userPwdConfirm) && user.getUserPwd().equals(userPwdConfirm)) {
			String salt = StringUtils.getRandomStr(CommonInfo.RANDOM_LEN);
			//采用盐+密码的方式加密
			String userPwd = new Md5Hash(user.getUserPwd(), salt, CommonInfo.HASH_INTERATIONS).toString();
			user.setUserPwd(userPwd);
			user.setUserSalt(salt);
			result = baseUserMapper.insterUser(user);
		}
		return result;
	}

	//用户登录
	@Override
	public User doLogin(UserLogin userLogin) {
        Subject subject = SecurityUtils.getSubject();
        if(ObjectUtils.ObjectIsNotNull(userLogin)) {
        	UsernamePasswordToken token =new UsernamePasswordToken(userLogin.getUserName(),userLogin.getUserPwd());
        	token.setRememberMe(userLogin.getRememberMe()==1?true:false);
        	subject.login(token);
        }
        //TODO 这个地方不太好这样写
        if(subject.isAuthenticated()) {
        	User user = baseUserMapper.getUserByUserName(userLogin.getUserName());
        	return user;
        }
		return null;
	}

}
